<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>扫雷提示版</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            display: flex;
            flex-direction: column;
            align-items: center;
            background-color: #f0f0f0;
            padding: 20px;
        }
        h1 {
            color: #333;
            margin-bottom: 20px;
        }
        .game-wrapper {
            display: flex;
            flex-direction: column;
            align-items: flex-start;
        }
        .game-container {
            display: flex;
            flex-direction: column;
            background-color: #ddd;
            padding: 10px;
            border-radius: 5px;
            box-shadow: 0 0 10px rgba(0,0,0,0.2);
            margin-bottom: 20px;
        }
        .row {
            display: flex;
        }
        .cell {
            width: 30px;
            height: 30px;
            border: 1px solid #999;
            background-color: #bbb;
            display: flex;
            justify-content: center;
            align-items: center;
            cursor: pointer;
            font-weight: bold;
            user-select: none;
            box-sizing: border-box;
        }
        .cell.revealed {
            background-color: #eee;
            cursor: default;
        }
        .cell.mine {
            background-color: #ff9999;
        }
        .cell.flagged {
            background-color: #99cc99;
        }
        .row-hint {
            width: 30px;
            height: 30px;
            display: flex;
            justify-content: center;
            align-items: center;
            font-weight: bold;
            color: #333;
            box-sizing: border-box;
        }
        .col-hint {
            width: 30px;
            height: 30px;
            display: flex;
            justify-content: center;
            align-items: center;
            font-weight: bold;
            color: #333;
            box-sizing: border-box;
        }
        .controls {
            margin-top: 10px;
            display: flex;
            flex-direction: column;
            align-items: center;
        }
        .difficulty-selector {
            margin-bottom: 15px;
        }
        button {
            padding: 8px 16px;
            margin: 0 5px;
            cursor: pointer;
            background-color: #4CAF50;
            color: white;
            border: none;
            border-radius: 4px;
        }
        button:hover {
            background-color: #45a049;
        }
        select {
            padding: 8px;
            border-radius: 4px;
            border: 1px solid #ddd;
        }
        .color-1 { color: blue; }
        .color-2 { color: green; }
        .color-3 { color: red; }
        .color-4 { color: darkblue; }
        .color-5 { color: brown; }
        .color-6 { color: teal; }
        .color-7 { color: black; }
        .color-8 { color: gray; }
        .game-info {
            margin-top: 15px;
            font-weight: bold;
        }
        .col-hints-container {
            display: flex;
            margin-left: 30px; /* 匹配行提示的宽度 */
        }
    </style>
</head>
<body>
<h1>扫雷提示版</h1>

<div class="difficulty-selector">
    <label for="difficulty">选择难度：</label>
    <select id="difficulty">
        <option value="easy">简单 (9×9, 10雷)</option>
        <option value="medium" selected>中等 (16×16, 40雷)</option>
        <option value="hard">困难 (16×30, 99雷)</option>
        <option value="custom">自定义</option>
    </select>

    <div id="custom-settings" style="display: none; margin-top: 10px;">
        <label>行数: <input type="number" id="custom-rows" min="5" max="30" value="16"></label>
        <label style="margin-left: 10px;">列数: <input type="number" id="custom-cols" min="5" max="40" value="16"></label>
        <label style="margin-left: 10px;">地雷数: <input type="number" id="custom-mines" min="1" max="500" value="40"></label>
    </div>

    <button id="start-btn">开始游戏</button>
</div>

<div class="game-wrapper">
    <div class="col-hints-container" id="col-hints-container">
        <!-- 列提示将在这里动态生成 -->
    </div>
    <div class="game-container" id="game-container">
        <!-- 游戏内容将通过JavaScript动态生成 -->
    </div>
</div>

<div class="controls">
    <button id="restart-btn">重新开始</button>
    <div class="game-info" id="status">请选择难度并开始游戏</div>
    <div class="game-info">剩余地雷: <span id="mines-left">0</span></div>
</div>

<script>
    document.addEventListener('DOMContentLoaded', function() {
        // 游戏配置
        const DIFFICULTIES = {
            easy: { rows: 9, cols: 9, mines: 10 },
            medium: { rows: 16, cols: 16, mines: 40 },
            hard: { rows: 16, cols: 30, mines: 99 }
        };

        let currentDifficulty = 'medium';
        let rows = DIFFICULTIES.medium.rows;
        let cols = DIFFICULTIES.medium.cols;
        let mines = DIFFICULTIES.medium.mines;

        let board = [];
        let revealed = [];
        let flagged = [];
        let gameOver = false;
        let rowMines = [];
        let colMines = [];
        let minesLeft = 0;

        const gameContainer = document.getElementById('game-container');
        const colHintsContainer = document.getElementById('col-hints-container');
        const statusDisplay = document.getElementById('status');
        const minesLeftDisplay = document.getElementById('mines-left');
        const restartBtn = document.getElementById('restart-btn');
        const startBtn = document.getElementById('start-btn');
        const difficultySelect = document.getElementById('difficulty');
        const customSettings = document.getElementById('custom-settings');

        // 事件监听
        restartBtn.addEventListener('click', initGame);
        startBtn.addEventListener('click', startGame);
        difficultySelect.addEventListener('change', handleDifficultyChange);

        function handleDifficultyChange() {
            currentDifficulty = difficultySelect.value;
            if (currentDifficulty === 'custom') {
                customSettings.style.display = 'block';
            } else {
                customSettings.style.display = 'none';
                const config = DIFFICULTIES[currentDifficulty];
                rows = config.rows;
                cols = config.cols;
                mines = config.mines;
            }
        }

        function startGame() {
            if (currentDifficulty === 'custom') {
                rows = parseInt(document.getElementById('custom-rows').value);
                cols = parseInt(document.getElementById('custom-cols').value);
                mines = parseInt(document.getElementById('custom-mines').value);

                // 验证自定义设置
                if (rows < 5 || rows > 30) {
                    alert('行数必须在5-30之间');
                    return;
                }
                if (cols < 5 || cols > 40) {
                    alert('列数必须在5-40之间');
                    return;
                }
                const maxMines = Math.floor(rows * cols * 0.85);
                if (mines < 1 || mines > maxMines) {
                    alert(`地雷数必须在1-${maxMines}之间`);
                    return;
                }
            }

            initGame();
        }

        function initGame() {
            board = [];
            revealed = Array(rows).fill().map(() => Array(cols).fill(false));
            flagged = Array(rows).fill().map(() => Array(cols).fill(false));
            gameOver = false;
            rowMines = new Array(rows).fill(0);
            colMines = new Array(cols).fill(0);
            minesLeft = mines;

            statusDisplay.textContent = '游戏进行中';
            minesLeftDisplay.textContent = minesLeft;

            // 初始化空白板
            for (let i = 0; i < rows; i++) {
                board[i] = new Array(cols).fill(0);
            }

            // 随机放置地雷
            let minesPlaced = 0;
            while (minesPlaced < mines) {
                const row = Math.floor(Math.random() * rows);
                const col = Math.floor(Math.random() * cols);

                if (board[row][col] !== -1) {
                    board[row][col] = -1; // -1 表示地雷
                    rowMines[row]++;
                    colMines[col]++;
                    minesPlaced++;

                    // 更新周围单元格的数字
                    for (let r = Math.max(0, row-1); r <= Math.min(rows-1, row+1); r++) {
                        for (let c = Math.max(0, col-1); c <= Math.min(cols-1, col+1); c++) {
                            if (board[r][c] !== -1) {
                                board[r][c]++;
                            }
                        }
                    }
                }
            }

            renderBoard();
        }

        function renderBoard() {
            gameContainer.innerHTML = '';
            colHintsContainer.innerHTML = '';

            // 调整单元格大小以适应大棋盘
            const cellSize = cols > 20 ? 25 : 30;
            const cellStyle = `width: ${cellSize}px; height: ${cellSize}px;`;

            // 创建列提示（单独容器，确保对齐）
            for (let c = 0; c < cols; c++) {
                const colHint = document.createElement('div');
                colHint.className = 'col-hint';
                colHint.textContent = colMines[c];
                colHint.style.cssText = cellStyle;
                colHintsContainer.appendChild(colHint);
            }

            // 创建游戏板
            for (let r = 0; r < rows; r++) {
                const rowElement = document.createElement('div');
                rowElement.className = 'row';

                // 添加行提示
                const rowHint = document.createElement('div');
                rowHint.className = 'row-hint';
                rowHint.textContent = rowMines[r];
                rowHint.style.cssText = cellStyle;
                rowElement.appendChild(rowHint);

                // 添加游戏单元格
                for (let c = 0; c < cols; c++) {
                    const cell = document.createElement('div');
                    cell.className = 'cell';
                    cell.dataset.row = r;
                    cell.dataset.col = c;
                    cell.style.cssText = cellStyle;

                    if (revealed[r][c]) {
                        cell.classList.add('revealed');
                        if (board[r][c] === -1) {
                            cell.classList.add('mine');
                            cell.textContent = '💣';
                        } else if (board[r][c] > 0) {
                            cell.textContent = board[r][c];
                            cell.classList.add(`color-${board[r][c]}`);
                        }
                    } else if (flagged[r][c]) {
                        cell.classList.add('flagged');
                        cell.textContent = '🚩';
                    }

                    cell.addEventListener('click', () => handleCellClick(r, c));
                    cell.addEventListener('contextmenu', (e) => {
                        e.preventDefault();
                        handleRightClick(r, c);
                    });

                    rowElement.appendChild(cell);
                }

                gameContainer.appendChild(rowElement);
            }
        }

        function handleCellClick(row, col) {
            if (gameOver || revealed[row][col] || flagged[row][col]) return;

            revealed[row][col] = true;

            if (board[row][col] === -1) {
                // 踩到地雷，游戏结束
                gameOver = true;
                revealAllMines();
                statusDisplay.textContent = '游戏结束！你输了！';
            } else if (board[row][col] === 0) {
                // 如果是空白单元格，自动展开相邻空白区域
                revealAdjacentCells(row, col);
            }

            if (checkWin()) {
                gameOver = true;
                statusDisplay.textContent = '恭喜你赢了！';
                flagAllMines();
            }

            renderBoard();
        }

        function handleRightClick(row, col) {
            if (gameOver || revealed[row][col]) return;

            if (flagged[row][col]) {
                flagged[row][col] = false;
                minesLeft++;
            } else {
                flagged[row][col] = true;
                minesLeft--;
            }

            minesLeftDisplay.textContent = minesLeft;
            renderBoard();
        }

        function revealAdjacentCells(row, col) {
            for (let r = Math.max(0, row-1); r <= Math.min(rows-1, row+1); r++) {
                for (let c = Math.max(0, col-1); c <= Math.min(cols-1, col+1); c++) {
                    if (!revealed[r][c] && !flagged[r][c]) {
                        revealed[r][c] = true;
                        if (board[r][c] === 0) {
                            revealAdjacentCells(r, c);
                        }
                    }
                }
            }
        }

        function revealAllMines() {
            for (let r = 0; r < rows; r++) {
                for (let c = 0; c < cols; c++) {
                    if (board[r][c] === -1) {
                        revealed[r][c] = true;
                    }
                }
            }
        }

        function flagAllMines() {
            for (let r = 0; r < rows; r++) {
                for (let c = 0; c < cols; c++) {
                    if (board[r][c] === -1) {
                        flagged[r][c] = true;
                    }
                }
            }
            minesLeft = 0;
            minesLeftDisplay.textContent = minesLeft;
        }

        function checkWin() {
            for (let r = 0; r < rows; r++) {
                for (let c = 0; c < cols; c++) {
                    if (board[r][c] !== -1 && !revealed[r][c]) {
                        return false;
                    }
                }
            }
            return true;
        }

        // 初始化UI
        handleDifficultyChange();
    });
</script>
</body>
</html>